package com.ldgk.pim.client.presenter;

import java.util.List;

import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.search.client.LocalResult;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.ldgk.pim.client.event.GLocalSearchEvent;
import com.ldgk.pim.client.event.GLocalSearchEventHandler;
import com.ldgk.pim.client.util.Util;
import com.ldgk.pim.client.view.MapView;
import com.ldgk.pim.data.Place;

/**
 * Handles map events 
 * @version 1.0
 *
 */
public class MapPresenter implements Presenter{
	private MapView view;
	
	/**
	 * Default constructor
	 * @param view
	 */
	public MapPresenter(MapView view){
		this.view = view;
		this.view.setPresenter(this);
		this.registerEventHandlers();
	}
	
	/**
	 * Clears all the markers over the map
	 */
	public void clearMap(){
		view.clearAll();
	}
	
	public void findPlacesInsideLatLng(LatLng start, LatLng end){
		view.clearDistributionPlaces();
		Util.persistenceService.findInsideBox(start.getLatitude(),start.getLongitude(),end.getLatitude(),end.getLongitude(), new AsyncCallback<List<Place>>() {
            public void onFailure(Throwable caught) {
              Window.alert("RPC to sendEmail() failed.");
            }
            public void onSuccess(List<Place> list) {
	             for(Place place:list){
	            	 view.addDistributionPlace(place);
	             }
            }
          });
	}
	
	/**
	 * Listens for google local results and shows them on the map as markers
	 */
	private void registerEventHandlers(){
		Util.eventbus.addHandler(GLocalSearchEvent.getType(), new GLocalSearchEventHandler(){
			@Override
			public void resultArrived(LocalResult result){
				view.addLocalResult(result);
			}
		});
	}
}
